package com.controller.ajax;

import com.dao.EmployeeDao;
import com.github.pagehelper.PageInfo;
import com.utils.JsonUtil;
import entity.EmpEntity;
import org.apache.ibatis.session.SqlSession;
import util.SqlSessionFactoryUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/pageDemo")
public class PageDemoServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 让客户端浏览器区别不同种类的数据
        resp.setContentType("application/json;charset=UTF-8");

        try (SqlSession sqlSession = SqlSessionFactoryUtil.getSession()){
            EmployeeDao mapper = sqlSession.getMapper(EmployeeDao.class);

            String pageNoString = req.getParameter("pageno");
            int pageNo = pageNoString == null || pageNoString.isEmpty() ? 1 : Integer.parseInt(pageNoString);
            int pageSize = 4;

            List<EmpEntity> list = mapper.getAllByPageHelper(pageNo, pageSize);
            PageInfo pageInfo = new PageInfo(list);
            String s = JsonUtil.object2String(pageInfo);
            resp.getWriter().print(s);
        }
    }
}
